<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
	<th:block th:include="include :: header('证券交易日历')" />
	<style>
		/* 交易日历样式 */
		.calendar-container {
			margin: 20px 0;
		}
		
		.calendar-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 20px;
		}
		
		.calendar-nav {
			display: flex;
			align-items: center;
			gap: 10px;
		}
		
		.calendar-nav button {
			padding: 5px 10px;
			border: 1px solid #ddd;
			background: white;
			cursor: pointer;
			border-radius: 3px;
		}
		
		.calendar-nav button:hover {
			background: #f5f5f5;
		}
		
		.calendar-title {
			font-size: 18px;
			font-weight: bold;
		}
		
		.calendar-table {
			width: 100%;
			border-collapse: collapse;
			border: 1px solid #ddd;
		}
		
		.calendar-table th,
		.calendar-table td {
			border: 1px solid #ddd;
			padding: 8px;
			text-align: center;
		}
		
		.calendar-table th {
			background-color: #f8f9fa;
			font-weight: bold;
		}
		
		.calendar-table .weekend {
			background-color: #f8f9fa;
			color: #6c757d;
		}
		
		.calendar-table .holiday {
			background-color: #fff3cd;
			color: #856404;
		}
		
		.calendar-table .trading-day {
			background-color: #d4edda;
			color: #155724;
		}
		
		.calendar-table .non-trading-day {
			background-color: #f8d7da;
			color: #721c24;
		}
		
		.calendar-table .today {
			border: 2px solid #007bff;
			font-weight: bold;
		}
		
		.sync-controls {
			margin-bottom: 20px;
			padding: 15px;
			background-color: #f8f9fa;
			border-radius: 5px;
		}
		
		.sync-controls .form-group {
			margin-bottom: 10px;
		}
		
		.sync-controls label {
			display: inline-block;
			width: 80px;
			font-weight: bold;
		}
		
		.sync-controls input,
		.sync-controls select {
			padding: 5px 10px;
			border: 1px solid #ddd;
			border-radius: 3px;
			margin-right: 10px;
		}
		
		.sync-controls button {
			padding: 8px 15px;
			background-color: #007bff;
			color: white;
			border: none;
			border-radius: 3px;
			cursor: pointer;
		}
		
		.sync-controls button:hover {
			background-color: #0056b3;
		}
		
		.sync-controls button:disabled {
			background-color: #6c757d;
			cursor: not-allowed;
		}
		
		/* 日历网格样式 - 使用网格布局 */
		#calendarGrid {
			display: grid;
			grid-template-columns: repeat(4, 1fr);
			grid-template-rows: repeat(3, 1fr);
			gap: 10px;
			grid-auto-flow: row;
			height: 100%;
		}
		
		.calendar-month {
			background: white;
			border: 1px solid #ddd;
			border-radius: 5px;
			padding: 15px;
			box-shadow: 0 2px 4px rgba(0,0,0,0.1);
			/* 自适应高度 */
			height: 100%;
			display: flex;
			flex-direction: column;
		}
		
		/* 明确指定每个月份的网格位置 */
		.calendar-month:nth-child(1) { grid-area: 1 / 1; } /* 1月 */
		.calendar-month:nth-child(2) { grid-area: 1 / 2; } /* 2月 */
		.calendar-month:nth-child(3) { grid-area: 1 / 3; } /* 3月 */
		.calendar-month:nth-child(4) { grid-area: 1 / 4; } /* 4月 */
		.calendar-month:nth-child(5) { grid-area: 2 / 1; } /* 5月 */
		.calendar-month:nth-child(6) { grid-area: 2 / 2; } /* 6月 */
		.calendar-month:nth-child(7) { grid-area: 2 / 3; } /* 7月 */
		.calendar-month:nth-child(8) { grid-area: 2 / 4; } /* 8月 */
		.calendar-month:nth-child(9) { grid-area: 3 / 1; } /* 9月 */
		.calendar-month:nth-child(10) { grid-area: 3 / 2; } /* 10月 */
		.calendar-month:nth-child(11) { grid-area: 3 / 3; } /* 11月 */
		.calendar-month:nth-child(12) { grid-area: 3 / 4; } /* 12月 */
		
		/* 响应式布局 - 保持4列布局 */
		@media (max-width: 1200px) {
			#calendarGrid {
				grid-template-columns: repeat(4, 1fr);
			}
			.calendar-month {
				padding: 10px;
			}
		}
		
		@media (max-width: 768px) {
			#calendarGrid {
				grid-template-columns: repeat(4, 1fr);
			}
			.calendar-month {
				padding: 8px;
				font-size: 12px;
			}
		}
		
		@media (max-width: 480px) {
			#calendarGrid {
				grid-template-columns: repeat(4, 1fr);
			}
			.calendar-month {
				padding: 5px;
				font-size: 10px;
			}
		}
		
		.calendar-month-title {
			text-align: center;
			font-size: 16px;
			font-weight: bold;
			margin-bottom: 10px;
			color: #333;
		}
		
		.calendar-month-table {
			width: 100%;
			border-collapse: collapse;
			font-size: 14px;
			/* 让表格填充剩余空间 */
			flex: 1;
		}
		
		/* 响应式字体大小 */
		@media (max-width: 768px) {
			.calendar-month-table th,
			.calendar-month-table td {
				font-size: 12px;
				height: 22px;
				padding: 3px 2px;
			}
		}
		
		@media (max-width: 480px) {
			.calendar-month-table th,
			.calendar-month-table td {
				font-size: 10px;
				height: 20px;
				padding: 2px 1px;
			}
		}
		
		.calendar-month-table th,
		.calendar-month-table td {
			border: 1px solid #eee;
			padding: 4px 3px;
			text-align: center;
			width: 10%;
			height: 24px;
			font-size: 14px;
		}
		
		.calendar-month-table th {
			background-color: #f8f9fa;
			font-weight: bold;
			font-size: 14px;
		}
		
		.calendar-month-table .trading-day {
			background-color: #d4edda;
			color: #155724;
		}
		
		.calendar-month-table .non-trading-day {
			background-color: #f8d7da;
			color: #721c24;
			font-weight: bold;
		}
		
		.calendar-month-table .weekend {
			background-color: #e9ecef;
			color: #495057;
			font-weight: normal;
		}
		
		.calendar-month-table .holiday {
			background-color: #fff3cd;
			color: #856404;
		}
		
		.calendar-month-table .other-month {
			color: #ddd;
		}
		
		/* 今天的标记样式 */
		.calendar-month-table .today {
			position: relative;
			background-color: #007bff !important;
			color: white !important;
			font-weight: bold;
		}
		
		.calendar-month-table .today::after {
			content: "今";
			position: absolute;
			top: 2px;
			right: 2px;
			font-size: 10px;
			font-weight: bold;
			color: white;
		}
		
		/* 休市的标记样式 */
		.calendar-month-table .holiday-mark {
			position: relative;
		}
		
		.calendar-month-table .holiday-mark::after {
			content: "休";
			position: absolute;
			top: 2px;
			right: 2px;
			font-size: 10px;
			font-weight: bold;
			color: #dc3545;
		}
		/* 页面布局优化 - 填充整个视口 */
		body {
			height: 100vh;
			overflow: hidden;
		}
		
		.container-fluid {
			height: 100vh;
			display: flex;
			flex-direction: column;
		}
		
		.row {
			flex: 1;
			overflow-y: auto;
		}
		
		/* 搜索区域固定高度 */
		.search-collapse {
			flex-shrink: 0;
			margin-bottom: 10px;
		}
		
		/* 日历容器自适应 */
		#calendarContainer {
			flex: 1;
			overflow-y: auto;
		}
		
		/* 日历网格容器 */
		#calendarGrid {
			padding-bottom: 20px;
		}
		
		/* 日历统计信息样式 */
		.calendar-stats {
			display: inline-block;
			padding: 8px 12px;
			background-color: #f8f9fa;
			border: 1px solid #dee2e6;
			border-radius: 4px;
			font-size: 14px;
			color: #495057;
			margin-right: 10px;
		}
		
		.calendar-stats .stat-item {
			margin-right: 15px;
		}
		
		.calendar-stats .stat-item:last-child {
			margin-right: 0;
		}
		
		.calendar-stats .stat-label {
			color: #6c757d;
		}
		
		.calendar-stats .stat-value {
			font-weight: bold;
			color: #007bff;
		}
	</style>
</head>
<body class="gray-bg">
	<div class="container-fluid">
		<div class="row">
			<div class="col-sm-12 search-collapse">
				<form id="formId" class="form-inline">
					<div class="form-group">
						<label>年份：</label>
						<input type="number" name="year" id="year" class="form-control" placeholder="请输入年份" min="1990" max="2099" value="2025">
					</div>
					<div class="form-group">
						<a class="btn btn-primary" onclick="loadCalendar()"><i class="fa fa-search"></i>&nbsp;查看日历</a>
					</div>
					<div class="form-group">
						<a class="btn btn-warning" onclick="resetCalendar()"><i class="fa fa-refresh"></i>&nbsp;重置</a>
					</div>
					<div class="form-group">
						<span id="calendarStats" class="calendar-stats">
							<!-- 统计信息将在这里显示 -->
						</span>
					</div>
					<div class="form-group">
						<a class="btn btn-success" onclick="syncTradingCalendar()">
							<i class="fa fa-refresh"></i> 同步交易日历
						</a>
					</div>
				</form>
			</div>
			
			<!-- 日历展示区域 -->
			<div class="col-sm-12" id="calendarContainer">
				<div id="calendarGrid" class="row">
					<!-- 12个月份的日历将在这里动态生成 -->
				</div>
			</div>
		</div>
	</div>
	
	<!-- 同步交易日历模态框 -->
	<div id="syncModal" class="modal fade" tabindex="-1" role="dialog">
		<div class="modal-dialog" role="document">
			<div class="modal-content">
				<div class="modal-header">
					<h4 class="modal-title">同步交易日历</h4>
					<button type="button" class="close" data-dismiss="modal" aria-label="Close">
						<span aria-hidden="true">&times;</span>
					</button>
				</div>
				<div class="modal-body">
					<form id="syncForm">
						<div class="form-group">
							<label for="syncYear">年份：</label>
							<input type="number" class="form-control" id="syncYear" name="year" min="1990" max="2099" value="2025" required>
						</div>
						<div class="form-group">
							<label for="syncMonth">月份：</label>
							<select class="form-control" id="syncMonth" name="month">
								<option value="">全年</option>
								<option value="1">1月</option>
								<option value="2">2月</option>
								<option value="3">3月</option>
								<option value="4">4月</option>
								<option value="5">5月</option>
								<option value="6">6月</option>
								<option value="7">7月</option>
								<option value="8">8月</option>
								<option value="9">9月</option>
								<option value="10">10月</option>
								<option value="11">11月</option>
								<option value="12">12月</option>
							</select>
						</div>
					</form>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
					<button type="button" class="btn btn-primary" onclick="confirmSync()">确定</button>
				</div>
			</div>
		</div>
	</div>
	
	<th:block th:include="include :: footer" />
	<script th:inline="javascript">
		var prefix = ctx + "security/trading-calendar";
		var tradingCalendarData = {};
		
		$(function() {
			// 页面加载时默认显示当前年份的日历
			loadCalendar();
		});
		
		// 加载日历
		function loadCalendar() {
			var year = $('#year').val() || new Date().getFullYear();
			loadTradingCalendarData(year);
		}
		
		// 重置日历
		function resetCalendar() {
			$('#year').val(new Date().getFullYear());
			loadCalendar();
		}
		
		// 加载交易日历数据
		function loadTradingCalendarData(year) {
			$.get(prefix + "/list", { year: year }, function(result) {
				console.log("API返回结果:", result);
				if (result.code == 0) { // AjaxResult成功状态码是0
					tradingCalendarData = {};
					// 将按月份分组的数据按日期组织
					if (result.data && typeof result.data === 'object') {
						$.each(result.data, function(month, monthData) {
							if (monthData && monthData.length > 0) {
								$.each(monthData, function(index, item) {
									if (item && item.date) {
										var dateStr = item.date.substring(0, 10); // 取日期部分
										tradingCalendarData[dateStr] = item;
									}
								});
							}
						});
					}
					console.log("处理后的交易日历数据:", tradingCalendarData);
					// 更新统计信息
					updateCalendarStats(year);
					// 生成12个月的日历
					generateCalendarGrid(year);
				} else {
					console.error("API返回错误:", result);
					$.modal.msgError("加载交易日历数据失败: " + (result.msg || "未知错误"));
				}
			}).fail(function(xhr, status, error) {
				console.error("请求失败:", xhr, status, error);
				$.modal.msgError("请求失败: " + error);
			});
		}
		
		// 生成12个月的日历网格
		function generateCalendarGrid(year) {
			var calendarGrid = $('#calendarGrid');
			calendarGrid.empty();
			
			// 使用弹性布局生成12个月份的日历
			for (var month = 1; month <= 12; month++) {
				var monthHtml = generateMonthCalendar(year, month);
				calendarGrid.append(monthHtml);
			}
		}
		
		// 生成单个月份的日历
		function generateMonthCalendar(year, month) {
			var monthNames = ['', '一月', '二月', '三月', '四月', '五月', '六月', 
							 '七月', '八月', '九月', '十月', '十一月', '十二月'];
			
			var html = '<div class="calendar-month">';
			html += '<div class="calendar-month-title">' + year + '年' + monthNames[month] + '</div>';
			html += '<table class="calendar-month-table">';
			
			// 表头
			html += '<thead><tr>';
			html += '<th>日</th><th>一</th><th>二</th><th>三</th><th>四</th><th>五</th><th>六</th>';
			html += '</tr></thead>';
			
			// 日历内容
			html += '<tbody>';
			
			var firstDay = new Date(year, month - 1, 1);
			var lastDay = new Date(year, month, 0);
			var firstWeekday = firstDay.getDay(); // 0=周日, 1=周一, ...
			var daysInMonth = lastDay.getDate();
			
			var currentDate = new Date();
			var isCurrentYear = year == currentDate.getFullYear();
			var isCurrentMonth = month == (currentDate.getMonth() + 1);
			
			// 生成日历行
			var day = 1;
			for (var week = 0; week < 6 && day <= daysInMonth; week++) {
				html += '<tr>';
				
				for (var weekday = 0; weekday < 7; weekday++) {
					if (week == 0 && weekday < firstWeekday) {
						// 上个月的日期
						var prevMonth = month == 1 ? 12 : month - 1;
						var prevYear = month == 1 ? year - 1 : year;
						var prevLastDay = new Date(prevYear, prevMonth, 0).getDate();
						var prevDay = prevLastDay - firstWeekday + weekday + 1;
						html += '<td class="other-month">' + prevDay + '</td>';
					} else if (day <= daysInMonth) {
						// 当前月的日期
						var dateStr = year + '-' + padZero(month) + '-' + padZero(day);
						var calendarItem = tradingCalendarData[dateStr];
						var isToday = isCurrentYear && isCurrentMonth && day == currentDate.getDate();
						var cellClass = getCellClass(calendarItem, weekday, isToday);
						
						html += '<td class="' + cellClass + '">' + day + '</td>';
						day++;
					} else {
						// 下个月的日期
						var nextDay = day - daysInMonth;
						html += '<td class="other-month">' + nextDay + '</td>';
						day++;
					}
				}
				
				html += '</tr>';
			}
			
			html += '</tbody></table></div>';
			return html;
		}
		
		// 获取单元格样式类
		function getCellClass(calendarItem, weekday, isToday) {
			var classes = [];
			
			// 今天的标记
			if (isToday) {
				classes.push('today');
			}
			
			// 周末标记
			if (weekday == 0 || weekday == 6) {
				classes.push('weekend');
			}
			
			// 交易日历数据标记
			if (calendarItem) {
				if (calendarItem.tradingDayFlag == 1) {
					classes.push('trading-day');
				} else {
					classes.push('non-trading-day');
					// 只有非周末的非交易日才添加休市标记
					if (weekday != 0 && weekday != 6) {
						classes.push('holiday-mark');
					}
				}
				
				if (calendarItem.holidayName) {
					classes.push('holiday');
				}
			}
			
			return classes.join(' ');
		}
		
		// 更新日历统计信息
		function updateCalendarStats(year) {
			var totalDays = 0;
			var tradingDays = 0;
			var nonTradingDays = 0;
			
			// 计算该年的总天数
			var isLeapYear = (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
			totalDays = isLeapYear ? 366 : 365;
			
			// 统计交易日和非交易日
			$.each(tradingCalendarData, function(dateStr, calendarItem) {
				if (calendarItem && calendarItem.tradingDayFlag !== undefined) {
					if (calendarItem.tradingDayFlag == 1) {
						tradingDays++;
					} else {
						nonTradingDays++;
					}
				}
			});
			
			// 更新显示
			var statsHtml = '<span class="stat-item">' +
				'<span class="stat-label">共</span> ' +
				'<span class="stat-value">' + totalDays + '</span>天 ' +
				'</span>' +
				'<span class="stat-item">' +
				'<span class="stat-label">开市</span> ' +
				'<span class="stat-value">' + tradingDays + '</span>天 ' +
				'</span>' +
				'<span class="stat-item">' +
				'<span class="stat-label">休市</span> ' +
				'<span class="stat-value">' + nonTradingDays + '</span>天' +
				'</span>';
			
			$('#calendarStats').html(statsHtml);
		}
		
		// 数字补零
		function padZero(num) {
			return num < 10 ? '0' + num : num;
		}
		
		// 同步交易日历
		function syncTradingCalendar() {
			$('#syncModal').modal('show');
		}
		
		// 确认同步
		function confirmSync() {
			var year = $('#syncYear').val();
			var month = $('#syncMonth').val();
			
			if (!year) {
				$.modal.msgError("请选择年份");
				return;
			}
			
			var url = prefix + "/sync";
			var data = { year: year };
			
			if (month) {
				url = prefix + "/sync/" + year + "/" + month;
				data.month = month;
			}
			
			$.modal.confirm("确定要同步" + year + (month ? "年" + month + "月" : "年") + "的交易日历数据吗？", function() {
				$.ajax({
					url: url,
					type: "POST",
					data: data,
					dataType: "json",
					success: function(result) {
						if (result.code == 0) {
							$.modal.msgSuccess("同步成功：" + result.msg);
							// 同步成功后重新加载日历
							loadCalendar();
							$('#syncModal').modal('hide');
						} else {
							$.modal.msgError("同步失败：" + result.msg);
						}
					},
					error: function(xhr, status, error) {
						$.modal.msgError("同步失败：" + error);
					}
				});
			});
		}
	</script>
</body>
</html>
